<?php

namespace Modules\Asset\Entities;

use \Modules\Chip\Entities\Chip;
use \Modules\Coupon\Entities\Coupon;
use \Modules\Activity\Entities\Ticket;

use ThrowException;

use Setting;

// 常规类资产 (如积分、红包) 
class SingleAsset
{
    public $asset;

    public function __construct($asset)
    {
        $this->asset = $asset;
    }

    // 获取碎片
    public function getChip()
    {
        $chip = null;

        if (@$this->asset['is_chip'] && @$this->asset['chip_id']) {
            $chip = Chip::getEntity([
                'id' => @$this->asset['chip_id'] ?: 0
            ], false);
        }

        return $chip;
    }


    // 发送给用户
    public function sendTo($user, $options)
    {
        $asset = $this->asset;
        $assetType = @$asset['type'];
        $assetTotal = @$asset['total'];

        // $description = @$options['description'];
        // $sendType = @$options['type'];

        // $order = @$options['order'];

        // 发放积分
        if ($assetType === 'score') {
            $user->asset('score')->in($assetTotal, $options);
        }
        // 发放红包
        elseif ($assetType === 'redpack') {
            $user->asset('redpack')->in($assetTotal, $options);
        }
        // 发放成长值
        elseif ($assetType === 'level_score') {
            $user->asset('level_score')->in($assetTotal, $options);
        }
        // 发放显示卡
        elseif ($assetType === 'show_card') {
            // $card = new Card('show_box');
            $user->card_asset('show_box')->in($assetTotal, $options);
        }
        // 发放排除卡
        elseif ($assetType === 'exclude_box') {
            // $card = new Card('show_box');
            $user->card_asset('exclude_box')->in($assetTotal, $options);
        }
        elseif ($assetType === 'coupon') {
            // $card = new Card('show_box');
            $couponId = $asset['coupon_id'];
            $coupon = Coupon::where('id', $couponId)->first();
            
            if ($coupon) {
                $coupon->pushTo($user, 'system', false);
            }
            // $user->card_asset('exclude_box')->in($assetTotal, $options);
        }
        elseif ($assetType === 'free_ticket') {
            $node = $options['node'];

            Ticket::in($user, $node, $assetTotal, @$options['description'], [
                'sub_type' => 1
            ]);
        }
        // 发放碎片
        elseif ($assetType === 'chip') {
            $chip = $this->getChip();
            $chipTotal = $this->getChipTotal();
            $user->chipAsset($chip->id)->in($assetTotal, $options);
        }

        return $asset;
    }
}
